package com.loit.business.utils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AESCoder {

public static void main(String args[]) {

        String content = "1234567890";
//        String password = "12345678123456781234567812345678";
        String password = "69ea10a4a5f5225271a6524734d70000";

        String first = password.substring(0, 16);
        String last = password.substring(16, 32);

//        // 加密
//        System.out.println("加密前：" + content);
//        byte[] encryptResult = encrypt(content, first);
//
//        System.out.println("第一阶段结果： "+parseByte2HexStr(encryptResult));
//        String firstResult = Base64.encodeBase64String(parseByte2HexStr(encryptResult).getBytes());
//        System.out.println("第一阶段Base64 结果： "+firstResult);
//
//        encryptResult = encrypt(Base64.encodeBase64String(parseByte2HexStr(encryptResult).getBytes()), last);
//
//        System.out.println("第二阶段结果： "+parseByte2HexStr(encryptResult));
//        String lastResult = Base64.encodeBase64String(parseByte2HexStr(encryptResult).getBytes());
//        System.out.println("第二阶段Base64 结果： "+lastResult);

    String lastResult = "eyJlcnJvcl9tZXNzYWdlIjp7ImVycm9yX2NvZGUiOiIwMDAyIiwiZXJyb3JfbXNnIjoi6K+35rGC5Y+C5pWwYXBwX2lk5qCh6aqM5aSx6LSlIn19";



        // 解密
        byte[] decryptResult = decrypt(hex2byte(new String(Base64.decodeBase64(lastResult))), last);
        String string = new String(decryptResult);
        System.out.println(string);
        decryptResult = decrypt(hex2byte(new String(Base64.decodeBase64(string))), first);
        System.out.println(new String(decryptResult));

//        // 加密
//        String s = encrypToBase64Str(content,password);
//
//        System.out.println(s);
//        // 解密
//        System.out.println(decryptFromBase64Str(s, password));

        }

        //2 转 16
        public static String byteToHexString(byte[] bytes) {
                StringBuffer sb = new StringBuffer(bytes.length);
                String sTemp;
                for (int i = 0; i < bytes.length; i++) {
                        sTemp = Integer.toHexString(0xFF & bytes[i]);
                        if (sTemp.length() < 2){
                                sb.append(0);
                        }
                        sb.append(sTemp.toUpperCase());
                }
                return sb.toString();
        }


        // 16 转 2
        public static byte[] hex2byte(String hex) throws IllegalArgumentException {
                if (hex.length() % 2 != 0) {
                        throw new IllegalArgumentException("invalid hex string");
                }
                char[] arr = hex.toCharArray();
                byte[] b = new byte[hex.length() / 2];
                for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
                        String swap = "" + arr[i++] + arr[i];
                        int byteint = Integer.parseInt(swap, 16) & 0xFF;
                        b[j] = new Integer(byteint).byteValue();
                }
                return b;
        }


/**
 * 加密
 *
 * @param content
 *            需要加密的内容
 * @param password
 *            加密密码
 * @return
 */
public static byte[] encrypt(String content, String password) {
        try {
        SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        byte[] byteContent = content.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return result; // 加密
        } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        } catch (InvalidKeyException e) {
        e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
        } catch (BadPaddingException e) {
        e.printStackTrace();
        }
        return null;
        }

/**
 * 解密
 *
 * @param content
 *            待解密内容
 * @param password
 *            解密密钥
 * @return
 */
public static byte[] decrypt(byte[] content, String password) {
        try {
        /*
         * KeyGenerator kgen = KeyGenerator.getInstance("AES");
         * kgen.init(128, new SecureRandom(password.getBytes())); SecretKey
         * secretKey = kgen.generateKey(); byte[] enCodeFormat =
         * secretKey.getEncoded(); SecretKeySpec key = new
         * SecretKeySpec(enCodeFormat, "AES");
         */
        SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(content);
        return result; // 加密
        } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        } catch (InvalidKeyException e) {
        e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
        } catch (BadPaddingException e) {
        e.printStackTrace();
        }
        return null;
        }

/**
 * 将二进制转换成16进制
 *
 * @param buf
 * @return
 */
public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
        String hex = Integer.toHexString(buf[i] & 0xFF);
        if (hex.length() == 1) {
        hex = '0' + hex;
        }
        sb.append(hex.toUpperCase());
        }
        return sb.toString();
        }

/**
 * 将16进制转换为二进制
 *
 * @param hexStr
 * @return
 */
public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
        return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
        int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
        int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
        16);
        result[i] = (byte) (high * 16 + low);
        }
        return result;
        }

public static String encrypToBase64Str(String content,String key){

        String first = key.substring(0, 16);
        String last = key.substring(16, 32);

        byte[] encryptResult = encrypt(content, first);
        encryptResult = encrypt(Base64.encodeBase64String(parseByte2HexStr(encryptResult).getBytes()), last);
        String lastResult = Base64.encodeBase64String(parseByte2HexStr(encryptResult).getBytes());

        return lastResult;
        }

public static String decryptFromBase64Str(String content,String key){

        String first = key.substring(0, 16);
        String last = key.substring(16, 32);

        byte[] decryptResult = decrypt(parseHexStr2Byte(new String(Base64.decodeBase64(content))), last);
        String string = new String(decryptResult);
        decryptResult = decrypt(parseHexStr2Byte(new String(Base64.decodeBase64(string))), first);
        return new String(decryptResult);
        }
        }